Paranthesis Matching Algorithm

The Parenthesis Matching Algorithm is an essential technique in computer science that checks the correctness of expressions containing various types of brackets, such as round brackets (parentheses), square brackets, and curly braces. This algorithm is widely used in parsing expressions in programming languages, evaluating mathematical expressions, and validating markup languages like HTML and XML. The main goal of this algorithm is to verify if the given expression has a proper and balanced arrangement of opening and closing brackets. A balanced expression is one where each opening bracket has a corresponding closing bracket in the correct order. The algorithm typically utilizes a stack data structure to process the given expression. It iterates through each character in the expression, and when an opening bracket is encountered, it is pushed onto the stack. When a closing bracket is encountered, the algorithm checks if the topmost element of the stack is the corresponding opening bracket; if it is, the opening bracket is popped from the stack. If the closing bracket does not match the topmost opening bracket or the stack is empty, the expression is deemed unbalanced, and the algorithm terminates. After processing every character in the expression, if the stack is empty, the expression is considered balanced, otherwise, it is unbalanced. This algorithm is efficient and robust, as it can handle nested and non-nested bracket sequences and can easily be extended to support multiple types of brackets.
#include <iostream>
#include <string>

using namespace std;

#define MAX 100

// -------------- stack --------------

char stack[MAX];
int top = -1;

void push(char ch)
{
	stack[++top] = ch;
}

char pop()
{
	return stack[top--];
}

// -------------- end stack -----------

char opening(char ch)
{
	switch (ch)
	{
	case '}':
		return '{';
	case ']':
		return '[';
	case ')':
		return '(';
	case '>':
		return '<';
	}
}

int main()
{

	string exp;
	int valid = 1, i = 0;
	cout << "Enter The Expression : ";
	cin >> exp;

	while (valid == 1 && i < exp.length())
	{
		if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<')
		{
			push(exp[i]);
		}
		else if (top >= 0 && stack[top] == opening(exp[i]))
		{
			pop();
		}
		else
		{
			valid = 0;
		}
		i++;
	}

	// makes sure the stack is empty after processsing (above)
	if (valid == 1 && top == -1)
	{
		cout << "\nCorrect Expression";
	}
	else
	{
		cout << "\nWrong Expression";
	}

	return 0;
}

LANGUAGE:

DARK MODE: